import React, { useEffect, useMemo, useState } from 'react'
import { List, message, Popover, Space } from 'antd'
import style from './Index.module.less'
import { $get, $put } from '@js/authRequest'
import { awaitWrap, confirmAction, formatDate } from '@js/tool'
import EditModal from './EditModal'
import { useUid } from '@hooks/userInfo'

async function getListRequest (caseid) {
  const res = await $get('/api/xapc/casenote', { params: { caseid } })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function deleteRequest (id) {
  const res = await $put(`/api/xapc/casenote/${id}`, { status: 0 })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function delHandle (id, callback) {
  const h = message.loading('删除中', 120)
  const [e] = await awaitWrap(deleteRequest(id))
  h()
  if (e === null) {
    message.success('删除成功', 1)
    callback()
  }
}

async function initList (caseid, setList, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(caseid))
  setLoading(false)
  if (e === null && d !== null) {
    d.sort((a, b) => {
      if (a.update_datetime && b.update_datetime) {
        return a.update_datetime - b.update_datetime
      }
      return a.create_datetime - b.create_datetime
    })
    setList(d)
  }
}

function Item ({ data, setEditing, setEditData, setLocking, refreshFn }) {
  const uid = useUid()
  const editable = useMemo(() => {
    return data.operatorid === uid
  }, [data, uid])
  return (
    <div className={style.item}>
      <div className={style['item-title']}>
        <span>{data.operator}</span>
        <Space>
          <span className={style.date}>{formatDate(data.update_datetime || data.create_datetime, 'YYYY-MM-DD HH:mm')}</span>
          {
            editable && (
              <>
                <a onClick={() => { setEditData(data); setEditing(true); setLocking(true) }}>编辑</a>
                <a onClick={() => { setLocking(true); confirmAction('您确定要删除该便签吗？', () => { delHandle(data.id, () => { refreshFn(); setLocking(false) }) }, () => setLocking(false)) }}>删除</a>
              </>
            )
          }
        </Space>
      </div>
      <div className={style['item-content']}>
        <span>{data.content}</span>
      </div>
    </div>
  )
}

function Content ({ loading, list, setEditing, setEditData, refreshFn, setLocking }) {
  return (
    <div className={style.content}>
      <div className={style.title}>
        <span>便签</span>
        <a onClick={() => { setEditing(true); setLocking(true) }}>添加</a>
      </div>
      <div className={style.scroller}>
        <List
          loading={loading} dataSource={list} renderItem={li => {
            return <Item data={li} setEditing={setEditing} setEditData={setEditData} setLocking={setLocking} refreshFn={() => { refreshFn() }} />
          }}
        />
      </div>
    </div>
  )
}

function Main ({ children, caseid, caseno, onlyadd, refreshFn }) {
  const [visible, setVisible] = useState(false)
  const [list, setList] = useState([])
  const [loading, setLoading] = useState(false)
  const [editing, setEditing] = useState(false)
  const [editData, setEditData] = useState(null)
  const [version, setVersion] = useState(Date.now())
  const [locking, setLocking] = useState(false)
  useEffect(() => {
    if (caseid && visible) {
      initList(caseid, setList, setLoading)
    }
  }, [caseid, visible, version])
  return (
    <>
      {
        onlyadd ? (
          <span onClick={() => { setEditing(true) }}>{children}</span>
        ) : (
          <Popover open={visible} overlayClassName={style.popover} arrow={false} trigger='click' content={<Content list={list} loading={loading} setEditData={setEditData} setEditing={setEditing} setLocking={setLocking} refreshFn={() => { setVersion(Date.now()); refreshFn() }} />} onOpenChange={(v) => { !locking && setVisible(v) }}>{children}</Popover>
        )
      }
      <EditModal caseid={caseid} caseno={caseno} visible={editing} editData={editData} hide={() => { setEditData(null); setEditing(false); setLocking(false) }} refreshFn={() => { setVersion(Date.now()); refreshFn() }} />
    </>
  )
}

export default Main
